﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Los.Core;

namespace Los.Barcode
{
    internal class RelationInterpreter : Interpreter
    {
        static private List<Relation> cache = Relation.GetAll().ToList();

        internal override string GetCode(object obj)
        {
            if (obj is Relation)
            {
                return "rela:id=" + obj.GetHashCode().ToString();
            }
            throw new Exception("Cannot encode object.");
        }

        internal override object GetObject(string code)
        {
            var param = GetParameters(code);
            int id;

            if (int.TryParse(param["id"], out id))
            {
                var rel = cache.Where(x => x.GetHashCode() == id).Take(1);
                if (rel.Count() > 0)
                    return rel.First();
                return null;
            }

            throw new Exception("Invalid parameter.");
        }

        internal override bool CanInterpret(object obj)
        {
            return (obj is Relation);
        }
    }
}
